package grooverse.util;

import groovy.util.BuilderSupport;

import java.util.Map;

public abstract class QualifiedBuilderSupport extends BuilderSupport {

    protected Object qualifier = null;

    private final Object fetchQualifier() {
        Object result = this.qualifier;
        this.qualifier = null;
        return result;
    }

    @Override
    protected final Object createNode(Object name) {
        return createNodeQualified(fetchQualifier(), name);
    }

    @Override
    protected final Object createNode(Object name, Object value) {
        return createNodeQualified(fetchQualifier(), name, value);
    }

    @SuppressWarnings("unchecked")
    @Override
    protected final Object createNode(Object name, Map attributes) {
        return createNodeQualified(fetchQualifier(), name, attributes);
    }

    @SuppressWarnings("unchecked")
    @Override
    protected final Object createNode(Object name, Map attributes, Object value) {
        return createNodeQualified(fetchQualifier(), name, attributes);
    }

    protected Object createNodeQualified(Object qualifier, Object name) {
        return createNodeQualified(qualifier, name, null, null);
    }

    protected Object createNodeQualified(Object qualifier, Object name, Object value) {
        return createNodeQualified(qualifier, name, null, value);
    }

    @SuppressWarnings("unchecked")
    protected Object createNodeQualified(Object qualifier, Object name, Map attributes) {
        return createNodeQualified(qualifier, name, attributes, null);
    }

    @SuppressWarnings("unchecked")
    protected abstract Object createNodeQualified(Object qualifier, Object name, Map attributes, Object value);

    @Override
    public Object getProperty(String name) {
        return new QualifiedBuilderDelegator(this, name);
    }

}
